/**
 * 1 获取缓存中的购物车数据
 * 2 获取缓存中的收货地址数据
 * 3 计算总价格和总数量
 */

 import {showModal, showToast} from "../../utils/asyncWx.js"
 import {request, requestPayment} from "../../request/request.js"
 Page({
   data: {
     address: {},
     cart: [],
     allChecked:false,
     totalPrice:0,
     totalNum:0
   },
   onShow() {
     // 从缓存中获取收货地址
     const address = wx.getStorageSync("address") || {};
     // 获取购物车里的数据
     let cart = wx.getStorageSync("cart") || [];
     cart = cart.filter(item=>item.checked);
     // 保存收货地址
     this.setData({address});
     //总数量和总价格的初始值
     this.setCart(cart);
   },
   setCart(cart){
     //1 计算总价格和总数量
      let totalPrice = 0;
      let totalNum = 0;
      cart.forEach(v => {
        if(v.checked){
          totalPrice += v.goods_price*v.num;
          totalNum += v.num;
        }
      });
     //将收货地址和购物车数据保存到数据中
      this.setData({
        cart,
        totalPrice,
        totalNum
      })
   },
   async handleOrderPay(){
      try{
        //1 判断缓存中是否存在token
      const token = wx.getStorageSync("token");
      //2 判断
      if(!token){
        wx.navigateTo({
          url: '/pages/auth/auth',
        });
        return;
      }
      // 3 创建订单
      //  3.1 准备请求头参数
      const header = {Authorization:token};
      //  3.2 准备 请求体参数
      const order_price  = this.data.totalPrice;
      const consignee_addr = this.data.address.all;
      const cart = this.data.cart;
      let goods = [];
      cart.forEach(v=>goods.push({
        goods_id:v.goods_id,
        goods_number:v.num,
        goods_price:v.goods_price
      }))
      const orderParams = {order_price,consignee_addr,goods}
      // 4 准备发送请求 创建订单 获取订单编号
      const res =await request({url:"/my/orders/create",
       data:orderParams, header, method:"POST"});
      const {order_number} = res.data.message
      // 5 发起 预支付接口
      const res2 = await request({url:"/my/orders/req_unifiedorder",
        header,data:{order_number}, method:"POST"});
      const {pay} = res2.data.message;
      // 6 发起微信支付
      // await requestPayment(pay);
      // // 7 查询后台 订单状态
      // const res3 = await request({url:"/my/orders/chkOrder",
      //   header,data:{order_number}, method:"POST"});
      // console.log(res3);
      // 8 支付成功了，跳转到订单页面
      await showToast({title:"支付成功！"});
      wx.navigateTo({
        url: '/pages/order/order?type=1',
      });
      }catch(err){
        await showToast({title:"支付失败！"});
        console.log(err);
      }
   }
 })

 
 